package knicker.api.servlet.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import knicker.api.servlet.auth.Authenticator;
import net.jeremybrooks.knicker.AccountApi;
import net.jeremybrooks.knicker.KnickerException;
import net.jeremybrooks.knicker.WordListApi;
import net.jeremybrooks.knicker.Knicker.ListType;
import net.jeremybrooks.knicker.dto.WordList;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class DelWordListServlet
 */
public class DelWordListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DelWordListServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			System.out.println(Authenticator.getAuthToken());
				
				
				WordListApi.deleteList(Authenticator.getAuthToken(), request.getParameter("listName"));
				
				List<WordList> lists = AccountApi.wordLists(Authenticator.getAuthToken());
				HashMap<String, String> mapLists = new HashMap<String, String>();
				System.out.println("-------");
				for(WordList ss : lists){
					System.out.println(ss.getName());
					mapLists.put(ss.getPermalink(), ss.getName());
				}	
				
				HashMap<String, String> map = new HashMap<String, String>();

				map.put("status", "0");
				map.put("message", "success");
				map.put("lists", mapLists.toString());
					// Convert to JSON string.
				JSONObject obj = new JSONObject();
				obj.putAll(map);
				  
				// Write JSON string.
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(obj.toString());
			} catch (KnickerException e) {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("status", "1");
				map.put("message", e.getMessage().toString());
				
				if(e.getMessage().toString().equals("Authentication token required.")){
					map.put("message", "token_required");
				}
				
				if(e.getMessage().toString().equals("Parameter id required.")){
					map.put("message", "name_required");
				}
				
				JSONObject obj = new JSONObject();
				obj.putAll(map);
				  
				// Write JSON string.
				response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(obj.toString());
			}
	}
}
